package com.bmob.lover.ui.fragment.cost

import android.graphics.Color
import android.view.View
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.ValueFormatter
import com.theone.common.ext.getPriceSpannableString
import com.theone.common.ext.regularizePrice
import com.bmob.lover.R
import com.bmob.lover.data.constant.CostConstant
import com.bmob.lover.data.model.bean.CostStatistics
import com.bmob.lover.databinding.FragmentCostStatisticsBinding
import com.bmob.lover.ui.fragment.base.BaseFragment
import com.bmob.lover.viewmodel.request.CostStatisticsRequestViewModel
import com.theone.mvvm.core.app.ext.showEmptyPage
import com.theone.mvvm.core.app.ext.showErrorPage
import com.theone.mvvm.core.app.ext.showLoadingPage
import com.theone.mvvm.core.app.ext.showSuccessPage
import java.util.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-29 16:24
 * @describe 消费统计
 * @email 625805189@qq.com
 * @remark
 */
class CostStatisticsFragment :
    BaseFragment<CostStatisticsRequestViewModel, FragmentCostStatisticsBinding>(),
    SwipeRefreshLayout.OnRefreshListener {

    override fun initView(root: View) {
        initRefreshLayout()
        initChart()
    }

    private fun initRefreshLayout() {
        setRefreshLayoutEnable(false)
        getDataBinding().refreshLayout.setOnRefreshListener(this@CostStatisticsFragment)
    }

    private fun initChart() {
        getDataBinding().pieChart.run {
            description = null //取消描述
            setNoDataText("没有数据")
            setEntryLabelTextSize(10f) //内容标题字体大小
            animateXY(1000, 1000)
            isDrawHoleEnabled = true
            setHoleColor(Color.WHITE)
            setTransparentCircleColor(Color.WHITE)
            setTransparentCircleAlpha(110)
            holeRadius = 58f
            transparentCircleRadius = 61f
            with(legend) {
                isEnabled = true //取消标注
                verticalAlignment = Legend.LegendVerticalAlignment.TOP
                horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
                orientation = Legend.LegendOrientation.VERTICAL
                setDrawInside(false)
                xEntrySpace = 7f
                yEntrySpace = 0f
                yOffset = 0f
            }
        }
    }

    override fun createObserver() {
        getViewModel().run {
            getResponseLiveData().observe(this@CostStatisticsFragment, androidx.lifecycle.Observer {
                setPieChartData(it)
            })

            getErrorLiveData().observe(this@CostStatisticsFragment, androidx.lifecycle.Observer {
                showErrorPage(it)
            })
            getFinallyLiveData().observe(this@CostStatisticsFragment, androidx.lifecycle.Observer {
                setRefreshLayoutEnable(true)
            })
        }
        mEventVm.getPublishLiveData().observe(this, androidx.lifecycle.Observer {
            // 无论收入或者支出都刷新统计界面 ( 分类除外 )
            if (it.startsWith("Cost") && !it.endsWith("Category")) {
                onRefresh()
            }
        })
    }

    private fun setPieChartData(costStatistics: List<CostStatistics>?) {
        if (costStatistics.isNullOrEmpty()) {
            showEmptyPage()
            return
        }
        val entries: MutableList<PieEntry> = ArrayList()
        val colors = IntArray(costStatistics.size)
        var earning = 0.0f
        var expense = 0.0f
        for ((i, item) in costStatistics.withIndex()) {
            colors[i] = if (item.type == CostConstant.EARNING) {
                earning = item.sumMoney
                R.color.cost_earning
            } else {
                expense = item.sumMoney
                R.color.cost_expense
            }
            entries.add(PieEntry(item.sumMoney, CostConstant.COST_TYPES[item.type]))
        }
        val dataSet = PieDataSet(entries, null).apply {
            setColors(colors, mActivity)
            sliceSpace = 2f //图形片段间距
        }
        val peiDate = PieData(dataSet).apply {
            setValueFormatter(object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return value.regularizePrice()
                }
            })
            setValueTextSize(13f) //内容值字体大小
            setValueTextColor(Color.WHITE) //内容值字体颜色
        }
        val money = (earning - expense).toDouble()
        val costColor = if (money > 0) {
            R.color.cost_earning
        } else {
            R.color.cost_expense
        }
        getDataBinding().pieChart.run {
            data = peiDate
            centerText =
                getPriceSpannableString(mActivity, money, color = costColor, proportion = 1.8f)
            invalidate()
        }
        showSuccessPage()
    }

    override fun onRefresh() {
        setRefreshLayoutEnable(enable = false, isRefresh = true)
        onPageReLoad()
    }

    override fun onLazyInit() {
        showLoadingPage()
        getViewModel().requestServer()
    }

    override fun onPageReLoad() {
        getViewModel().isFirst = false
        getViewModel().isFresh = true
        onLazyInit()
    }

    private fun setRefreshLayoutEnable(enable: Boolean, isRefresh: Boolean = false) {
        getDataBinding().refreshLayout.run {
            isEnabled = enable
            isRefreshing = isRefresh
        }
    }

}